<?php
/**
 * Created by PhpStorm.
 * User: zhangxilu
 * Date: 2017/12/25
 * Time: 下午10:55
 */

namespace backend\models;


use common\logic\AdminUserLogic;
use yii\base\Model;

class ChangePassForm extends Model
{
    public $password;
    public $newpassword;
    public $passwordagain;


    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['password', 'newpassword', 'passwordagain'], 'string', 'min' => 6, 'max' => 50],
            [['password', 'newpassword', 'passwordagain'], 'required'],
            ['passwordagain', 'compare', 'compareAttribute' => 'newpassword', 'operator' => '=='],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'password' => '旧密码',
            'newpassword' => '新密码',
            'passwordagain' => '确认密码',
        ];
    }

    public function change(){

        $user = AdminUserLogic::instance()->getById(\Yii::$app->user->getId());
        if($user->validatePassword($this->password)){
            $user->setPassword($this->newpassword);
            return $user->save();
        }
        $this->addError('password', '密码错误');
    }
}